package dict

import (
	"context"

	"github.com/blog-zero/api/admin/internal/common/errorx"
	"github.com/blog-zero/api/admin/internal/svc"
	"github.com/blog-zero/api/admin/internal/types"
	"github.com/blog-zero/rpc/sys/sysclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type DictDeleteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDictDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DictDeleteLogic {
	return &DictDeleteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DictDeleteLogic) DictDelete(req *types.DeleteDictReq) (*types.DeleteDictResp, error) {
	parentsResp, err := l.svcCtx.DictService.DictChildenParentsCount(l.ctx, &sysclient.DictChildenParentsCountReq{
		Ids: req.Ids,
	})
	if err != nil {
		logx.WithContext(l.ctx).Errorf("根据ids: %v,查询所有ids所属子字典异常:%s", req.Ids, err.Error())
		return nil, errorx.NewDefaultError("删除字典失败")
	}

	if parentsResp.ParentsCount > 0 {
		logx.WithContext(l.ctx).Errorf("根据ids:查询所有ids所属子字典数量:%d", parentsResp.ParentsCount)
		return nil, errorx.NewDefaultError("必须删除所有子字典")
	}

	_, err1 := l.svcCtx.DictService.DictDelete(l.ctx, &sysclient.DictDeleteReq{
		Ids: req.Ids,
	})

	if err1 != nil {
		logx.WithContext(l.ctx).Errorf("根据parentId: %v,删除字典异常:%s", req.Ids, err.Error())
		return nil, errorx.NewDefaultError("删除字典失败")
	}

	return &types.DeleteDictResp{
		Code:    "000000",
		Message: "删除字典成功",
	}, nil
}
